package com.lengxf.mqtt.config;

import lombok.Data;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.integration.mqtt.core.DefaultMqttPahoClientFactory;
import org.springframework.integration.mqtt.core.MqttPahoClientFactory;
import org.springframework.util.Assert;

import java.util.List;


@Data
@ConfigurationProperties(prefix = "emq")
public class MqttConfiguration {

    private String protocol;

    private String host;

    private Integer port;

    private String username;

    private String password;

    private String clientName;

    private List<String> inboundTopic;

    public String[] getInboundTopic() {
        Assert.notEmpty(this.inboundTopic, "please configure emq inbound topic ...");
        return inboundTopic.toArray(new String[]{});
    }

    public MqttConnectOptions mqttConnectOptions() {
        MqttConnectOptions mqttConnectOptions = new MqttConnectOptions();
        mqttConnectOptions.setServerURIs(new String[]{buildServerUri()});
        mqttConnectOptions.setUserName(username);
        mqttConnectOptions.setPassword(password.toCharArray());
        mqttConnectOptions.setAutomaticReconnect(true);
        mqttConnectOptions.setKeepAliveInterval(10);
        return mqttConnectOptions;
    }

    private String buildServerUri() {
        return protocol.trim() + "://" + host.trim() + ":" + port;
    }

    @Bean
    public MqttPahoClientFactory mqttClientFactory() {
        DefaultMqttPahoClientFactory factory = new DefaultMqttPahoClientFactory();
        factory.setConnectionOptions(mqttConnectOptions());
        return factory;
    }
}
